<template>
     
  <div>
    <!-- 顶部卡片 -->
    <el-card class="card">
      <div class="right">
        <el-upload
          class="upload-demo"
          action="https://jsonplaceholder.typicode.com/posts/"
          multiple
        >
          <el-button size="small" type="primary">
            <i class="el-icon-upload"></i>
            导入</el-button
          >
        </el-upload>
        <el-button type="primary" size="small" class="xz"
          ><i class="el-icon-plus"></i> 新 增 员 工</el-button
        >
      </div>
    </el-card>
    <!-- 内容区域表格区域 -->
    <el-card>
      <el-table
        :data="userList"
        border
        style="width: 100%"
        :default-sort="{ prop: 'user', order: 'descending' }"
      >
        <el-table-column type="index" label="序号" width="80">
        </el-table-column>
        <el-table-column prop="user" sortable label="姓名" width="120">
        </el-table-column>
        <el-table-column prop="phone" sortable label="手机号" width="120">
        </el-table-column>
        <el-table-column prop="jobNumber" sortable label="工号" width="120">
        </el-table-column>
        <el-table-column prop="shape" sortable label="聘用形式" width="120">
        </el-table-column>
        <el-table-column prop="branch" sortable label="部门" width="300%">
        </el-table-column>
        <el-table-column prop="Induction" sortable label="入职时间" width="120">
          <template slot-scope="scope">
            <div>
              {{ scope.row.Induction | dateFormat }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="work"
          sortable
          label="是否在职"
          width="120"
        ></el-table-column>
        <el-table-column prop="state" sortable label="状态" width="120">
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="240">
          <template slot-scope="scope">
            <el-button type="text" size="small">查看</el-button>
            <el-button type="text" size="small">转正</el-button>
            <el-button
              type="text"
              size="small"
              @click="transfer(scope.row)"
              :disabled="scope.row.responsible ? true : false"
              >调岗</el-button
            >
            <el-button type="text" size="small">离职</el-button>
            <el-button type="text" size="small">角色</el-button>
            <el-button type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!--    弹出调岗的对话框 -->
    <el-dialog :visible.sync="PostdialogVisible" width="50%" title="调岗">
      <el-form
        ref="PostFrom"
        :model="PostFromData"
        :rules="rules"
        size="medium"
        label-width="81px"
      >
        <el-form-item label="当前用户">
          <el-input
            v-model="PostFromData.user"
            :disabled="true"
            :style="{ width: '100%' }"
          ></el-input>
        </el-form-item>
        <el-form-item label="当前部门">
          <el-input
            v-model="PostFromData.breach"
            :disabled="true"
            :style="{ width: '100%' }"
          ></el-input>
        </el-form-item>
        <el-form-item label="部门" prop="b_id">
          <el-cascader
            v-model="PostFromData.b_id"
            :options="branchlist"
            :props="b_idProps"
            :style="{ width: '100%' }"
            placeholder="请选择部门"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handelConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { users, edituser } from "@/axios/user";
import { branchs } from "@/axios/brank";
import { mapMutations, mapState } from "vuex";
export default {
  name: "Vue-deparment-index",
  props: {},
  data() {
    return {
      userList: [],
      branchId: [],
      branchlist: [],
      breachs: [],
      PostFromData: {
        u_id: "",
        user: "",
        breach: "",
        b_id: [],
      },
      rules: {
        b_id: [
          {
            required: true,
            message: "请选择一个部门",
            trigger: "change",
          },
        ],
      },
      PostdialogVisible: false,
      b_idProps: {
        multiple: false,
        label: "b_name",
        value: "_id",
        checkStrictly: true,
      },
    };
  },
  mounted() {
    this.getUser();
    this.getdata();
  },
  methods: {
    // 获取用户
    async getUser() {
      let { data } = await users();
      if (data.code != 200) {
        this.$message.error(data.msg);
        return;
      }
      this.userList = data.data;
      if (["管理员", "超级管理员"].indexOf(this.user.user) == -1) {
        this.userList = this.userList.filter((item) => {
          return this.branchId.includes(item.b_id._id);
        });
        // if(){}
        this.breachs.forEach((item) => {
          if (this.branchId.includes(item._id)) {
            var istrue = true;
            for (let i in this.userList) {
              if (this.userList[i]._id == item.responsible._id) {
                if(Array.isArray(this.userList[i].b_id)){
                  this.userList[i].b_id.push(item);
                }
                istrue = false;
                break;
              }
            }
            if (istrue) {
              item.responsible.b_id = [item];
              item.responsible.responsible = 1;
              this.userList.unshift(item.responsible);
            }
          }
        });
      }
      this.userList.forEach((item) => {
        if (!Array.isArray(item.b_id)) {
          item.b_id = [item.b_id];
        }
        item.branch = [];
        item.b_id.forEach((item1) => {
          item.branch.push(item1.b_name);
        });
        item.branch = item.branch.join(" | ");
      });
    },
    // 对部门数据进行解析
    getchildren(datalist, data) {
      datalist.forEach((item) => {
        item.children = data.filter((item1) => {
          return item._id == item1.b_id._id;
        });
        item.children =
          this.getchildren(item.children, data) == []
            ? this.getchildren(item.children, data)
            : item.children;
      });
      return datalist;
    },
    // 获取部门数据
    async getdata() {
      let { data } = await branchs();
      if (data.code != 200) {
        this.$message.error(data.msg);
        return;
      }
      this.breachs = data.data;
      // 获取到一级部门
      let datalist = data.data.filter((item) => {
        return !item.b_id;
      });
      // 获取到非一级部门
      let dataA = data.data.filter((item) => {
        return item.b_id;
      });
      this.branchlist = this.getchildren(datalist, dataA);
      this.branchId = this.getBreachId(this.branchlist);
    },
    // 获取下级部门id
    getBranchIdList(data) {
      let a = [];
      data.forEach((item) => {
        a.push(item._id);
        if (item.children) {
          a.push(...this.getBranchIdList(item.children));
        }
      });
      return a;
    },
    // 获取当前用户负责的部门或当前用户所归属的部门id
    getBreachId(data) {
      let datalist = [];
      data.forEach((item) => {

        if (item.responsible._id == this.user._id) {
          // 当前用户为部门负责人
          datalist.push(item._id);
          datalist.push(...this.getBranchIdList(item.children));
        } else {
          // 如果当前用户为该部门的成员 
          // console.log(this.user) ;
          if (item._id == this.user.b_id._id) {
            return datalist.push(item._id);
          } else if (item.children) {
            // 当前部门有下级部门
            this.getBreachId(item.children);
          }
        }
      });
      return datalist;
    },
    // 弹出调岗对话框调岗
    transfer(data) {
      this.PostFromData.user = data.user;
      this.PostFromData.u_id = data._id;
      this.PostFromData.breach = data.b_id ? data.b_id.b_name : "暂无";
      this.PostdialogVisible = true;
    },
    // 提交调岗
    handelConfirm() {
      this.$refs["PostFrom"].validate(async (valid) => {
        if (!valid) return;
        let b_id = this.PostFromData.b_id[this.PostFromData.b_id.length - 1];
        let { data } = await edituser(this.PostFromData.u_id, { b_id: b_id });
        this.getUser();
        this.close();
      });
    },
    // 关闭调岗对话框
    close() {
      this.PostdialogVisible = false;
      this.$refs.PostFrom.resetFields();
    },
  },
  computed: {
    ...mapState(["user"]),
  },
};
</script>

<style lang="scss" scoped>
.card {
  margin-bottom: 20px;
}
.right {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  flex-direction: row;
}
.xz {
  margin-left: 20px;
}
::v-deep(.el-table th.el-table__cell > .cell) {
  text-align: center;
}
</style>
